package com.jinsilu.freight.ui.fragment;

import static com.hjq.http.EasyUtils.postDelayed;

import android.content.Context;
import android.graphics.Color;
import android.os.Bundle;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.Spanned;
import android.text.TextPaint;
import android.text.method.LinkMovementMethod;
import android.text.style.ClickableSpan;
import android.text.style.UnderlineSpan;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.widget.AppCompatTextView;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.blankj.utilcode.util.BusUtils;
import com.blankj.utilcode.util.LogUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.fondesa.recyclerviewdivider.DividerDecoration;
import com.hdgq.locationlib.LocationOpenApi;
import com.hdgq.locationlib.entity.ShippingNoteInfo;
import com.hdgq.locationlib.listener.OnResultListener;
import com.hjq.base.BaseDialog;
import com.hjq.base.action.BundleAction;
import com.hjq.base.action.ClickAction;
import com.hjq.http.EasyHttp;
import com.hjq.http.listener.HttpCallback;
import com.hjq.http.listener.OnHttpListener;
import com.hjq.permissions.OnPermissionCallback;
import com.hjq.permissions.Permission;
import com.hjq.permissions.XXPermissions;
import com.hjq.widget.view.BlankNoteCountdownView;
import com.jinsilu.freight.R;
import com.jinsilu.freight.action.ToastAction;
import com.jinsilu.freight.databinding.UnfinishedWaybillFragmentBinding;
import com.jinsilu.freight.helper.CommonHelper;
import com.jinsilu.freight.http.model.HttpData;
import com.jinsilu.freight.http.model.HttpListData;
import com.jinsilu.freight.http.request.ApplyWhiteApi;
import com.jinsilu.freight.http.request.GetWaybillListApi;
import com.jinsilu.freight.http.response.DataBean;
import com.jinsilu.freight.http.response.WaybillBean;
import com.jinsilu.freight.other.AppConfig;
import com.jinsilu.freight.other.MTLConstants;
import com.jinsilu.freight.ui.activity.BrowserActivity;
import com.jinsilu.freight.ui.activity.HomeActivity;
import com.jinsilu.freight.ui.activity.ImagePreviewActivity;
import com.jinsilu.freight.ui.activity.UploadLoadingActivity;
import com.jinsilu.freight.ui.activity.UploadUnloadingActivity;
import com.jinsilu.freight.ui.adapter.UnfinishedWaybillAdapter;
import com.jinsilu.freight.ui.dialog.MessageDialog;
import com.jinsilu.freight.ui.dialog.WaitDialog;
import com.jinsilu.freight.widget.BrowserView;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadMoreListener;

import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;

public class UnfinishedWaybillFragment extends Fragment
        implements ClickAction, BundleAction, ToastAction, OnHttpListener {

    /**
     * 加载对话框
     */
    private BaseDialog mDialog;
    /**
     * 对话框数量
     */
    private int mDialogTotal;

    /**
     * 当前加载对话框是否在显示中
     */
    public boolean isShowDialog() {
        return mDialog != null && mDialog.isShowing();
    }

    /**
     * 显示加载对话框
     */
    public void showDialog() {
        mDialogTotal++;
        postDelayed(() -> {
            if (mDialogTotal > 0 && !isHidden()) {
                if (mDialog == null) {
                    mDialog = new WaitDialog.Builder(getContext())
                            .setCancelable(false)
                            .create();
                }
                if (!mDialog.isShowing()) {
                    mDialog.show();
                }
            }
        }, 300);
    }

    /**
     * 隐藏加载对话框
     */
    public void hideDialog() {
        if (mDialogTotal > 0) {
            mDialogTotal--;
        }

        if (mDialogTotal == 0 && mDialog != null && mDialog.isShowing() && !isHidden()) {
            mDialog.dismiss();
        }
    }

    /**
     * 根布局
     */
    private View mRootView;

    private UnfinishedWaybillFragmentBinding mBinding;

    private UnfinishedWaybillAdapter mAdapter;

    public static final String TAG_NEED_TO_REFRESH_WAYBILL = "TagNeedToRefreshWaybill";

    @BusUtils.Bus(tag = TAG_NEED_TO_REFRESH_WAYBILL, sticky = true)
    public void onRefresh() {
        /*通知刷新*/
        if (CommonHelper.isLogin()) {
            mCurrentPage = 1;
            getWaybillData();
        }
    }

    public static UnfinishedWaybillFragment newInstance() {
        return new UnfinishedWaybillFragment();
    }

    private Integer mCurrentPage = 1;

    @Override
    public void onAttach(@NonNull Context context) {
        super.onAttach(context);
    }

    @Override
    public void onDetach() {
        super.onDetach();
    }


    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        mBinding = UnfinishedWaybillFragmentBinding.inflate(inflater, container, false);
        mRootView = mBinding.getRoot();

        setOnClickListener(mBinding.waybillStartDate, mBinding.waybillEndDate, mBinding.waybillFilter);

        // 先屏蔽加载，有数据再放开
        mBinding.refresh.setEnableLoadMore(false);

        mBinding.recycler.setLayoutManager(new LinearLayoutManager(getContext()));

        DividerDecoration.builder(requireContext())
                .asSpace().size(10, TypedValue.COMPLEX_UNIT_DIP)
                .showSideDividers()
                .showFirstDivider()
                .showLastDivider()
                .build()
                .addTo(mBinding.recycler);
        mAdapter = new UnfinishedWaybillAdapter(new ArrayList<>());

        mBinding.recycler.setAdapter(mAdapter);

        mAdapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
//                WaybillBean bean = (WaybillBean) adapter.getData().get(position);
//                Intent intent = new Intent(requireActivity(), WaybillDetailsActivity.class);
//                intent.putExtra("waybill", bean);
//                startActivity(intent);
            }
        });

        mAdapter.addChildClickViewIds(R.id.tv_open_the_blank_note, R.id.item_waybill_more, R.id.item_waybill_upload_unloading, R.id.iv_view_loading_image, R.id.iv_view_unloading_image);
        mAdapter.setOnItemChildClickListener((adapter, view, position) -> {
            if (1 != CommonHelper.getCertificationStatus()) {
                toast("认证后方可操作");
                return;
            }
            WaybillBean waybillBean = (WaybillBean) adapter.getData().get(position);
            int id = view.getId();
            if (id == R.id.item_waybill_more) {
                // 消息对话框
                new MessageDialog.Builder(view.getContext())
                        // 标题可以不用填写
                        .setTitle("")
                        // 内容必须要填写
                        .setMessage("是否确认删除？")
                        // 确定按钮文本
                        .setConfirm(getString(R.string.common_confirm))
                        // 设置 null 表示不显示取消按钮
                        .setCancel(getString(R.string.common_cancel))
                        // 设置点击按钮后不关闭对话框
                        //.setAutoDismiss(false)
                        .setListener(new MessageDialog.OnListener() {

                            @Override
                            public void onConfirm(BaseDialog dialog) {
                                deleteWaybill(waybillBean);
                            }

                            @Override
                            public void onCancel(BaseDialog dialog) {

                            }
                        })
                        .show();
            } else if (id == R.id.item_waybill_upload_unloading) {
                // 场景：上传装车磅单后，因为某种原因删除了已装车的运单信息
                // 1:待装货(抢完单) 上传装车磅单的时候判断是否存在未完成的缓存定位运单信息，有的话调用结束
                if (waybillBean.getWaybillStatus() == 1) {
                    try {
                        ShippingNoteInfo shippingNoteInfo = (ShippingNoteInfo) CommonHelper.getSavedObject("sdk", ShippingNoteInfo.class);
                        if (shippingNoteInfo != null && shippingNoteInfo.getShippingNoteNumber().equals(waybillBean.getWaybillNumber())) {
                            stopLocation(shippingNoteInfo);
                        }
                    } catch (Exception e) {
                        LogUtils.e(e.getMessage());
                    }
                }
                // 上传装卸车磅单
                getLocationPermission(waybillBean);
            } else if (id == R.id.iv_view_loading_image) {
                showImageView(waybillBean.getUploadImgUrl());
            } else if (id == R.id.iv_view_unloading_image) {
                showImageView(waybillBean.getUnloadImgUrl());
            } else if (id == R.id.tv_open_the_blank_note) {
                showBlankNotePrivacyDialog(waybillBean.getWaybillNumber());
            }
        });


        mBinding.refresh.setOnRefreshLoadMoreListener(new OnRefreshLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                mCurrentPage += 1;
                getWaybillData();
            }

            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                mCurrentPage = 1;
                getWaybillData();
            }
        });

        return mRootView;
    }

    /**
     * 网络货运SDK 停止定位上传卸车运单号
     */
    private void stopLocation(ShippingNoteInfo shippingNoteInfo) {

        ShippingNoteInfo[] shippingNoteNumbers = new ShippingNoteInfo[]{shippingNoteInfo};
        /*
         * context 上下文
         * vehicleNumber 车牌号
         * driverName 司机姓名
         * remark 备注
         * shippingNoteNumbers 运单信息列表
         * listener 结果回调函数
         */
        LocationOpenApi.auth(getContext(), AppConfig.getPackageName(), AppConfig.getAppSecurity(), AppConfig.getEnterpriseSenderCode(), AppConfig.getBuildType(), new OnResultListener() {
            @Override
            public void onFailure(String errorCode, String errorMsg) {
                hideDialog();
//                finish();
                LogUtils.e(String.format("监管平台SDK认证错误：ErrorCode%s ErrorMsg%s", errorCode, errorMsg));
            }

            @Override
            public void onSuccess(List<ShippingNoteInfo> list) {
                /*
                 * context 上下文
                 * vehicleNumber 车牌号
                 * driverName 司机姓名
                 * remark 备注
                 * shippingNoteNumbers 运单信息列表
                 * listener 结果回调函数
                 */
                LocationOpenApi.stop(getContext(), shippingNoteInfo.getVehicleNumber(), shippingNoteInfo.getDriverName(), "[98]清除无效运单缓存", shippingNoteNumbers, new OnResultListener() {
                    @Override
                    public void onFailure(String errorCode, String errorMsg) {
                        hideDialog();
//                        finish();
                        LogUtils.e(String.format("监管平台SDK停止错误：ErrorCode%s ErrorMsg%s", errorCode, errorMsg));
                    }

                    @Override
                    public void onSuccess(List<ShippingNoteInfo> list) {
                        hideDialog();
                        CommonHelper.clearObj("sdk");
//                        finish();
                        BusUtils.postSticky(HomeActivity.TAG_CANCEL_COUNT_DOWN); // 发送消息取消倒计时上传数据
                    }
                });

            }
        });
    }

    /**
     * 展示白条协议
     */
    private void showBlankNotePrivacyDialog(String waybillNumber) {
        // 弹出白条使用协议
        new BaseDialog.Builder(getActivity())
                .setContentView(R.layout.dialog_blank_note_agreement)
                .setAnimStyle(BaseDialog.ANIM_SCALE)
                .setCanceledOnTouchOutside(false)
                //.setText(id, "我是预设置的文本")
                .setOnClickListener(R.id.bcv_agree, (BaseDialog.OnClickListener<BlankNoteCountdownView>) (dialog, view) -> {
                    dialog.dismiss();
                    // 调用保存按钮
                    applyBlankNote(waybillNumber);
                })
                .setOnClickListener(R.id.tv_btn_disagree, (BaseDialog.OnClickListener<TextView>) (dialog, view) -> {
                    dialog.dismiss();
                    // 调用拒绝按钮
                })
                .addOnShowListener(dialog -> {
                    BrowserView webView = ((BrowserView) dialog.getContentView().findViewById(R.id.wv_browser_view));
                    if (null != webView) {
                        webView.loadUrl(AppConfig.getAgreementUrl());
                    }
                    BlankNoteCountdownView countdownView = dialog.getContentView().findViewById(R.id.bcv_agree);
                    if (null != countdownView) {
                        countdownView.setTotalTime(10);
                        countdownView.start();
                    }
                })
                .addOnCancelListener(dialog -> {
                })
                .addOnDismissListener(dialog -> {
                    BrowserView webView = ((BrowserView) dialog.getContentView().findViewById(R.id.wv_browser_view));
                    if (null != webView) {
                        webView.removeAllViews();
                        webView.destroy();
                    }
                })
                .setOnKeyListener((dialog, event) -> {
//                    toast("按键代码：" + event.getKeyCode());
                    return false;
                })
                .show();
    }

    /**
     * 申请开通白条支付
     *
     * @param waybillNumber 运单号
     */
    private void applyBlankNote(String waybillNumber) {
        // 上传装车磅单
        EasyHttp.put(this)
                .api(new ApplyWhiteApi()
                        .setWaybillNumber(waybillNumber))
                .request(new HttpCallback<HttpData<Void>>(this) {

                    @Override
                    public void onSucceed(HttpData<Void> data) {
                        toast(data.getMessage());
                        mBinding.refresh.autoRefresh();
                    }
                });
    }

    /**
     * 展示隐私权限弹框
     */
    private void showPrivacyDialog(List<String> permissions) {
        // 自定义对话框
        BaseDialog privacyDialog = new BaseDialog.Builder(getContext())
                .setContentView(R.layout.dialog_privacy)
                .setAnimStyle(BaseDialog.ANIM_SCALE)
                .setOnClickListener(R.id.btn_dialog_custom_ok, (BaseDialog.OnClickListener<Button>) (dialog, view) -> {
                    dialog.dismiss();
                    toast("请手动授予始终定位权限");
                    // 如果是被永久拒绝就跳转到应用权限系统设置页面
                    XXPermissions.startPermissionActivity(getContext(), permissions);
                })
                .setOnClickListener(R.id.btn_dialog_custom_cancel, (BaseDialog.OnClickListener<Button>) (dialog, view) -> {
                    dialog.dismiss();
                })
                .addOnShowListener(dialog -> {
                })
                .addOnCancelListener(dialog -> {
                })
                .addOnDismissListener(dialog -> {
                })
                .setOnKeyListener((dialog, event) -> {
//                    toast("按键代码：" + event.getKeyCode());
                    return false;
                })
                .create();

        AppCompatTextView privacyContent = privacyDialog.getContentView().findViewById(R.id.tv_privacy_content);
        String content = "请您务必审慎阅读，应网络货运监管平台要求，需要在您运输过程中使用定位权限，获取您的所在位置并上传至网络货运监管平台；定位使用高德提供的定位服务，关于高德定位隐私权限可以阅读《高德地图开放平台隐私权政策》了解详细信息。如您同意，请点击“同意”开始接受我们的服务。";
        SpannableStringBuilder spannableString = new SpannableStringBuilder(content);
        int privateBeginIndex = content.indexOf("《");
        int privateEndIndex = content.indexOf("》") + 1;
        setUserPolicy(spannableString, privateBeginIndex, privateEndIndex, "privacy");
        //设置点击事件，加上这句话才有效果
        privacyContent.setMovementMethod(LinkMovementMethod.getInstance());
        //设置点击后的颜色为透明（有默认背景）
        privacyContent.setHighlightColor(getResources().getColor(R.color.transparent));
        privacyContent.setText(spannableString);
        privacyDialog.show();
    }

    public void setUserPolicy(SpannableStringBuilder spannableString, int start, int end, String type) {
        //设置部分文字点击事件
        ClickableSpan clickableSpan = new ClickableSpan() {

            @Override
            public void updateDrawState(TextPaint ds) {
                super.updateDrawState(ds);
                //超链接形式的下划线，false 表示不显示下划线，true表示显示下划线
                ds.setUnderlineText(false);
            }

            @Override
            public void onClick(View widget) {
                BrowserActivity.start(widget.getContext(), "https://lbs.amap.com/pages/privacy/");
            }
        };
        spannableString.setSpan(clickableSpan, start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
//        //设置部分文字颜色
//        ForegroundColorSpan foregroundColorSpan = new ForegroundColorSpan(Color.parseColor("#5e89ef"));

        //使用ForegroundColorSpan添加点击事件会出现冲突
        UnderlineSpan colorSpan = new UnderlineSpan() {
            @Override
            public void updateDrawState(TextPaint ds) {
                ds.setColor(Color.parseColor("#5e89ef"));//设置颜色
            }
        };
        spannableString.setSpan(colorSpan, start, end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
    }

    @Override
    public void onResume() {
        super.onResume();
        // 未登录、未认证
        if (!CommonHelper.isLogin() || 1 != CommonHelper.getCertificationStatus()) {
            mBinding.refresh.setEnableRefresh(false);
            mAdapter.setEmptyView(R.layout.layout_empty_order_view);
        } else {
            mBinding.refresh.setEnableRefresh(true);
            mCurrentPage = 1;
            getWaybillData();
        }
    }

    /**
     * 获取定位权限，成功后调用停止定位
     * 运单状态 1:待装货(抢完单) 2:运输中(上传装车磅单后) 3:已卸车(上传卸车磅单后) 4:装车磅单打回 5:卸车磅单打回 6:装卸车打回 7:支付中 8:已支付 9:开票中 10:已开票
     */
    private void getLocationPermission(WaybillBean waybillBean) {
        XXPermissions.with(this)
                .permission(new String[]{
                        Permission.ACCESS_FINE_LOCATION,
                        Permission.ACCESS_COARSE_LOCATION})
                .request(new OnPermissionCallback() {

                    @Override
                    public void onGranted(List<String> permissions, boolean all) {
                        if (all) {
                            if (2 == waybillBean.getWaybillStatus() || 5 == waybillBean.getWaybillStatus()) {
                                UploadUnloadingActivity.start(requireActivity(), waybillBean);
                            } else if (1 == waybillBean.getWaybillStatus() || 4 == waybillBean.getWaybillStatus() || 6 == waybillBean.getWaybillStatus()) {
                                UploadLoadingActivity.start(requireActivity(), waybillBean);
                            }
                        }
                    }

                    @Override
                    public void onDenied(List<String> permissions, boolean never) {
                        showPrivacyDialog(permissions);
                    }
                });
    }

    /**
     * 查看图片
     *
     * @param image 图片地址
     */
    private void showImageView(String image) {
        ArrayList<String> images = new ArrayList<>();
        images.add(image);
        ImagePreviewActivity.start(getContext(), images, images.size() - 1);
    }

    private void deleteWaybill(WaybillBean waybillBean) {

        // 删除运单
        EasyHttp.delete(this)
                .api(String.format("api/waybill/%s", waybillBean.getWaybillNumber()))
                .request(new HttpCallback<HttpData<DataBean<Void>>>(this) {

                    @Override
                    public void onSucceed(HttpData<DataBean<Void>> data) {
                        toast(data.getMessage());
                        mAdapter.remove(waybillBean);
                    }
                });
    }

    private void getWaybillData() {

        // 未完成运单列表
        EasyHttp.get(this)
                .api(new GetWaybillListApi().setPageNum(mCurrentPage).setPageSize(10).setType(MTLConstants.WAYBILL_UNFINISHED))
                .request(new HttpCallback<HttpListData<WaybillBean>>(this) {

                    @Override
                    public void onSucceed(HttpListData<WaybillBean> data) {
                        CommonHelper.finishedLoading(mBinding.refresh);
                        List<WaybillBean> waybillBeans = data.getData();
                        if (null == waybillBeans || waybillBeans.isEmpty()) {
                            mAdapter.setEmptyView(R.layout.layout_empty_order_view);
                            mBinding.refresh.setEnableLoadMore(false);
                        } else {
                            mBinding.refresh.setEnableLoadMore(Integer.parseInt(data.getMessage()) / 10f > mCurrentPage);
                            if (mCurrentPage == 1)
                                mAdapter.setList(waybillBeans);
                            else
                                mAdapter.addData(waybillBeans);
                        }


                    }
                });
    }

    @Override
    public void onClick(View v) {
        int id = v.getId();
        if (id == R.id.waybill_start_date) {
            toast("开始时间");
        } else if (id == R.id.waybill_end_date) {
            toast("至今");
        } else if (id == R.id.waybill_filter) {
            toast("筛选");
        }
    }

    @Override
    public void onStart() {
        super.onStart();
        BusUtils.register(this);
    }

    @Override
    public void onStop() {
        super.onStop();
        BusUtils.unregister(this);
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        mBinding = null;
        if (isShowDialog()) {
            hideDialog();
        }
        mDialog = null;
    }

    @Nullable
    @Override
    public View getView() {
        return mRootView;
    }

    @Nullable
    @Override
    public Bundle getBundle() {
        return getArguments();
    }

    @Override
    public <V extends View> V findViewById(int id) {
        return null;
    }

    /**
     * {@link OnHttpListener}
     */

    @Override
    public void onStart(Call call) {
        showDialog();
    }

    @Override
    public void onSucceed(Object result) {
//        if (result instanceof HttpData) {
//            toast(((HttpData) result).getMessage());
//        }
    }

    @Override
    public void onFail(Exception e) {
        toast(e.getMessage());
        if (mAdapter.getData().isEmpty())
            mAdapter.setEmptyView(R.layout.layout_empty_order_view);
        CommonHelper.finishedLoading(mBinding.refresh);
    }

    @Override
    public void onEnd(Call call) {
        hideDialog();
    }
}
